﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using FY2013.Model.UserModels;
using FY2013.Business;
using FY2013.Model;
using System.Text;

namespace FY2013.WebUI.Controllers
{

    [HandleError]
    public class UserController : Controller
    {
        protected override void Initialize(RequestContext requestContext)
        {

            base.Initialize(requestContext);
        }

        public ActionResult Login()
        {
            return View();
        }
        public ActionResult GetPassword()
        {
            return View();
        }

        public ActionResult LogOff()
        {


            return RedirectToAction("Index", "Home");
        }


        public ActionResult Register()
        {

            List<SelectListItem> options = GetSelectListItems();
            ViewData["languages"] = options;
            return View();
        }

        private  List<SelectListItem> GetSelectListItems()
        {
            List<SelectListItem> options = new List<SelectListItem>();

            string langNo = string.Empty;
            if (Request.UserLanguages != null && Request.UserLanguages.Count() > 0)
            {
                langNo = Request.UserLanguages[0];
            }

            foreach (Languages language in LanguageHelper.GetTopLanguage(10))
            {
                if (language.LanguageNo == langNo)
                {
                    options.Add(new SelectListItem() { Text = language.LanguageName, Value = language.LanguageNo, Selected=true });
                    continue;
                }
                options.Add(new SelectListItem() { Text = language.LanguageName, Value = language.LanguageNo });
            }
            return options;
        }

        [HttpPost]
        public ActionResult Register(RegisterAccountModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    UserHelper.Register(model, Request.UserHostAddress, Url.Content("~/avatar"));

                    if (model.Password != model.ConfirmPassowrd)
                    {
                        throw new Exception("两次输入的密码必须一致！");
                    }

                    Session["Mail"] = model.Account + "|" + model.Email;
                    return RedirectToAction("RegisterSuccess", new { id = EncryptHelper.DESEncrypt(model.Email) });
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError(string.Empty,ex.Message);
                }
            }
            List<SelectListItem> options = GetSelectListItems();
            ViewData["languages"] = options;
            return View(model);
        }

        public ActionResult RegisterSuccess(string id)
        {
            ViewData["WebSiteCaption"] = WebSiteHelper.GetWebSiteCaption();
            ViewData["Account"] = string.Empty;
            if(string.IsNullOrWhiteSpace(id))
            {
                return View();
            }  
            string activeValue=EncryptHelper.DESDecrypt(id);
            string[]value = activeValue.Split('|');
            string account=value[0];
            string mail=value[1];

            if (Session["Mail"] != null && !string.IsNullOrWhiteSpace(Session["Mail"].ToString()) && mail == Session["Mail"])
            {
                Session["Mail"] = null;
                string subject = string.Format("欢迎注册{0},请激活账号！",WebSiteHelper.GetWebSiteCaption());
                
                string key=EncryptHelper.ToBase64(EncryptHelper.DESEncrypt(EncryptHelper.DESEncrypt(account)));
                string activeLink=Url.Action("Activate","User",new {id=key});
                string body = string.Format(WebSiteHelper.GetEmailBody(), WebSiteHelper.GetWebSiteCaption(), activeLink);
                MailHelper.SendEmail(mail, subject,body);
            }
            
            return View();
        }

        public ActionResult VerifyCodeImage()
        {
            string verifyCode = VerifyCodeGenerator.GetRandomText();
            HttpContext.Cache["verifyCode"] = verifyCode;
            return File(VerifyCodeGenerator.CreateImage(verifyCode), @"image/jpeg");
        }

        [Authorize]
        public ActionResult ChangePassword()
        {

            return View();
        }

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

    }
}
